package com.xpec.c4.db.hibernate.manager;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class QueryResInterceptor extends EmptyInterceptor{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6798449059813471538L;
	
	public static int TYPE_NONE =0;
	
	public static int TYPE_LOG = 1;
	
	public static int TYPE_SELECT_LOG = 2;
	
	
	
	/**
	 * 預寫入的資料表名稱
	 */
	private String viewName;
	
	/**
	 * 讀取月份
	 */
	private Date selectMonth;
	
	/**
	 * 類別
	 */
	private int type; 
	
	
	public QueryResInterceptor(){
		type = TYPE_LOG;
	}
	
	/**
	 * 主動做設定
	 * @param className
	 */
	public void setViewName(String className)
	{
		type = TYPE_SELECT_LOG;
		viewName = ConfigurationManager.getRecyleTableName(className);
		
		if(viewName==null)
		{
			type = TYPE_NONE;
		}
	}
	
	public void setMonth(Date month)
	{
		selectMonth = month;
	}
	
	
	public boolean onSave(Object entity,Serializable id,
			Object[] state,String[] propertyNames,Type[] types)
			throws CallbackException 
	{
		String className = entity.getClass().getSimpleName();
		viewName = ConfigurationManager.getRecyleTableName(className);
		return false;
	}
	
	
	public String onPrepareStatement(String sql)
	{
		if(viewName==null || type == TYPE_NONE)
		{
			return sql;
		}
		
		
		//當前月份
		int  month=0;
		Calendar calendar = Calendar.getInstance();
		if(type == TYPE_LOG)
		{
					month =calendar.get(Calendar.MONTH) + 1;
		}
		else if(type == TYPE_SELECT_LOG)
		{
					calendar.setTime(selectMonth);
					month =  calendar.get(Calendar.MONTH)+1;
		}
		String tableName=viewName+"_"+month;
		sql = sql.replace(viewName,tableName);
		viewName = null;
		return sql;
	}
}
